import React, { useState } from 'react'
import styles from './index.module.scss'
import NavBar from '@/components/NavBar'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import { useDispatch } from 'react-redux'
import { login, sendValidationCode } from '@/store/actions/login'
import { useHistory, useLocation } from 'react-router'
import { Toast } from 'antd-mobile'
import * as Yup from 'yup'
import classNames from 'classnames'

export default function Login() {
  const dispatch = useDispatch()
  const [time, setTime] = useState(0)
  const history = useHistory()
  const localtion = useLocation()
  const onExtraClick = async () => {
    console.log(123)
    // 倒计时禁止点击
    if (time > 0) return

    if (!/^1[1-9]\d{9}$/.test(mobile)) {
      formik.setTouched({ mobile: true })
      return
    }
    await dispatch(sendValidationCode(mobile))
    Toast.success('获取成功', 1)

    setTime(60)
    const timer = setInterval(() => {
      setTime((time) => {
        if (time === 1) {
          clearInterval(timer)
        }
        return time - 1
      })
    }, 1000)
  }

  const formik = useFormik({
    initialValues: {
      mobile: '',
      code: '',
    },
    onSubmit: async (values) => {
      // console.log(values)
      await dispatch(login(values))
      Toast.success('登录成功', 1)
      const pathname = localtion.state?.from || '/home'
      history.replace(pathname)
    },
    // validate(values) {
    //   const errors = {}
    //   if (!values.mobile) {
    //     errors.mobile = '手机号码不能为空'
    //   }
    //   if (!values.code) {
    //     errors.code = '验证码不能为空'
    //   }
    //   return errors
    // },
    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[1-9]\d{9}$/, '手机号码格式错误'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码错误'),
    }),
  })

  const {
    values: { mobile, code },
    handleSubmit,
    handleChange,
    touched,
    errors,
    handleBlur,
    isValid,
  } = formik

  return (
    <div className={styles.root}>
      <NavBar onLeftClick={() => history.push('/home')}>登录</NavBar>
      <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          <div className="input-item">
            <Input
              name="mobile"
              placeholder="请输入手机号"
              autoComplete="off"
              values={mobile}
              onChange={handleChange}
              maxLength={11}
              onBlur={handleBlur}
            />
            {touched.mobile && errors.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : null}
          </div>

          <div className="input-item">
            <Input
              name="code"
              extra={time === 0 ? '短信验证码' : time + '秒后获取'}
              placeholder="请输入验证码"
              autoComplete="off"
              values={code}
              onChange={handleChange}
              onBlur={handleBlur}
              maxLength={6}
              onExtraClick={onExtraClick}
            />
            {touched.code && errors.code ? (
              <div className="validate">{errors.code}</div>
            ) : null}
          </div>
          <button
            type="submit"
            className={classNames('login-btn', { disabled: !isValid })}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
